<template>
  <div class="pi-manage">
    <el-form class="btn_con" v-model="form">
      <el-row gutter="8">
        <el-col :span="4">
          <el-form-item>
            <el-input
              v-model="queryParams.pi"
              placeholder="请输入PI"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="20" class="add_btn">
          <el-button type="primary" size="medium" @click="handleQuery">搜索</el-button>
          <el-button size="medium" @click="resetQuery">重置</el-button>
          <el-button size="medium" type="primary" @click="toCreatePage()">生成PI</el-button>
        </el-col>
      </el-row>
    </el-form>
    <div>

      <el-table :loading="loading"  :data="tableData" style="width: 100%;" :height="tableHeight">
        <el-table-column label="PI" align="center" prop="pi" :show-overflow-tooltip="true" width="120" />
        <el-table-column label="客户信息" align="center">
          <el-table-column label="客户名称" align="center" prop="billCustomer" :show-overflow-tooltip="true">
            <template #default="{ row }"> {{ row.billCustomer }} </template>
          </el-table-column>
          <el-table-column label="客户公司" align="center" prop="billCompany" :show-overflow-tooltip="true">
            <template #default="{ row }"> {{ row.billCompany }} </template>
          </el-table-column>
          <el-table-column label="客户邮箱" align="center" prop="billEmail" :show-overflow-tooltip="true" min-width="120">
            <template #default="{ row }"> {{ row.billEmail }} </template>
          </el-table-column>
          <el-table-column label="客户电话" align="center" prop="billTel" :show-overflow-tooltip="true" min-width="120">
            <template #default="{ row }"> {{ row.billTel }} </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="收货信息" align="center" min-width="300">
          <template #default="{ row }">
            <div v-if="row.shipOthers" class="ship-card">
              <div v-for="(item, index) in JSON.parse(row.shipOthers)" :key="item.id" class="ship-card-item mb10">
                <div class="card-title">收货人{{++index }}</div>
                <div class="card-content">
                  <div>收货人: {{ item.shipConsignee }}</div>
                  <div>公司: {{ item.shipCompany }}</div>
                  <div>电话: {{ item.shipTel }}</div>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          fixed="right"
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="160"
        >
          <template #default="{ row }">
            <el-button
                @click="handleEdit(row)"
                size="small"
                type="primary"
                link
            >
              编辑
            </el-button>
            <el-button
                @click="handlePlaceAnOrder(row)"
                size="small"
                type="primary"
                link
            >
              下单
            </el-button>
            <el-button size="small" type="primary" link @click="exportPDF(row)">导出PDF</el-button>
            <el-button
                @click="handleDel(row)"
                size="small"
                type="danger"
                link
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination_con">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="pagination.page"
          :total="pagination.total"
          small background layout="prev, pager, next"
        />
      </div>
    </div>
  </div>
</template>
  
<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import api from '/@/api/email/index';
import { Local } from '/@/utils/storage';
const router = useRouter();
const queryParams = ref({
  userId: Local.get('userId'),
  pi: null
});
const tableData = ref([]);
const tableHeight = ref(500);

defineOptions({ name: 'PIIndex' })

const form = ref<any>({});
const loading = ref(false);

const pagination = ref({
  page: 1,
  size: 10,
  total: 0
});


const resetQuery = () => {
  queryParams.value.pi = null;
  pagination.value.page = 1
  handleQuery()
}

const handleDel = (row: any) => {
  ElMessageBox.confirm(`确认删除PI为：'${row.pi}'的数据吗?`, '提示', { cancelButtonText: '取消', confirmButtonText: '确认' }).then(async () => {
    const res = await api.pi.delPi(row.id);
    if (res.code === 200) {
      ElMessage({ type: 'success', message: '操作成功' });
      getList();
    }
  });
}

const toCreatePage = () => {
  router.push('/PI/create')
}

const exportPDF = async (row: { id: any; }) => {
  try {
    const result = await api.pi.exportPdf({
      id: row.id
    })
    console.log(result, 'result')
    const url = window.URL.createObjectURL(new Blob([result.data], { type: 'application/pdf' }))
    const link = document.createElement('a')
    link.href = url
    const fileName = `PI_${new Date().getTime()}.pdf`
    link.setAttribute('download', fileName) // 指定下载后的文件名，需要与后端设置的Content-Disposition中的文件名一致或相似
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url) // 释放URL对象
  } catch (error) {
    
  }
}

const handleQuery = () => {
  pagination.value.page = 1;
  getList();
};

const getList = async () => {
  loading.value = true
  const res = await api.pi.getList({
    pageNum: pagination.value.page,
    pageSize: pagination.value.size,
    ...queryParams.value
  });
  loading.value = false;
  if (res.code === 200) {
    tableData.value = res.data;
    pagination.value.total = res.total;
  }
};

const handleEdit = (row: any) => {
  router.push(`/PI/edit/${row.id}`);
};

const handlePlaceAnOrder = (row: any) => {
  router.push({
    name: 'orderCreate',
    query: {
      pi: row.pi
    }
  });
}

const handleCurrentChange = (page: number) => {
  pagination.value.page = page;
  getList();
};

onMounted(() => {
  getList();

  const setTableHeight = () => {
    tableHeight.value = window.innerHeight - 130 // 80 为顶部距离，根据实际情况设置
  }
  setTableHeight()
  window.addEventListener('resize', setTableHeight);
});
</script>
<style lang="scss" scoped>
.ship-card {
  display: flex;
  flex-direction: column;
  width: 100%;
  .ship-card-item {
    display: flex;
    flex-direction: column;
    .card-title {
      font-weight: bold;
      text-align: start;
      background: #efefef;
      padding:  2px 10px;
    }
    .card-content {
      display: flex;
      padding:  2px 10px;
      div {
        flex: 1;
      }
    }
  }
}

.pi-manage {
  width: 100%;
  height: 100vh;
  padding: 20px;
}

.pagination_con {
  display: flex;
  justify-content: end;
  padding: 10px;
  background: #fff;
}

.btn_con {
  padding: 7px 10px;
  margin-bottom: 10px;
}

.add_btn {
  flex: 1;
  display: flex;
  justify-content: right;
  align-items: center;
}

.inquuiry_table {
  margin-left: 30px;
}
</style>
  